package me.yricky.alia.ui.gdsStructPage

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.yricky.alia.ui.StateViewModel
import me.yricky.alia.utils.gds.GDS
import me.yricky.alia.utils.gds.GDS2Iterator
import java.io.File

/**
 * @author Yricky
 * @date 2022/1/27
 */
class GDSStructViewModel:StateViewModel<GDSStructViewModel.ViewState>(){
    data class ViewState(
        val isLoading:Boolean = true,
        val records:List<GDS.Record.Raw> = emptyList(),
        val showFilter:Boolean = true,
        val filter:Set<GDS.RecordType> = GDS.RecordType.values().toSet()
    )
    override fun initState(): ViewState = ViewState()

    fun setShowFilter(b:Boolean){
        _viewState.value = _viewState.value.copy(
            showFilter = b
        )
    }

    fun clearFilter(){
        _viewState.value = _viewState.value.copy(
            filter = emptySet()
        )
    }

    fun resetFilter(){
        _viewState.value = _viewState.value.copy(
            filter = GDS.RecordType.values().toSet()
        )
    }

    fun filterExclude(rt: GDS.RecordType){
        _viewState.value = _viewState.value.copy(
            filter = _viewState.value.filter.minus(rt)
        )
    }

    fun filterInclude(rt: GDS.RecordType){
        _viewState.value = _viewState.value.copy(
            filter = _viewState.value.filter.plus(rt)
        )
    }

    fun loadFile(path:String){
        coroutineScope.launch {
            _viewState.value = _viewState.value.copy(isLoading = true)
            _viewState.value = _viewState.value.copy(
                records = withContext(Dispatchers.IO){
                    val fInS = File(path).inputStream()
                    GDS2Iterator(fInS).asSequence().toMutableList()
                },
                isLoading = false
            )
        }
    }

}